﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Parameters
{
    public partial class Form1 : Form
    {
        const string ConStr = "Data Source=.;Initial Catalog=ADO_NET_Simple;Integrated Security=True";
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 绑定数据到 datagridview
        /// </summary>
        private void BindData()
        {
            //查询语句
            string sql = "select * from Students";
            //标记是否有 where关键字
            bool hasWhere = false;
            List<SqlParameter> parameters=new List<SqlParameter>();
            if (txtName.Text.Trim()!="")
            {
                sql += " where StudentName like @name";
                hasWhere = true;
                parameters.Add(new SqlParameter("name", string.Format("%{0}%", txtName.Text.Trim())));
            }

            if (nudAge.Text.Trim()!="")
            {
                if (!hasWhere)
                {
                    sql += " where StudentAge = @age";
                }
                else
                {
                    sql += " and StudentAge = @age";
                }
                parameters.Add(new SqlParameter("age", nudAge.Text.Trim()));
            }
            

            DataTable dt = ExecuteDataTable(sql, parameters.ToArray());

            dgvStudentList.DataSource = dt;
        }

        /// <summary>
        /// 获取 DataTable
        /// </summary>
        /// <param name="cmdText"></param>
        /// <param name="parameters">qlParameters 对象</param>
        /// <returns></returns>
        private DataTable ExecuteDataTable(string cmdText,params SqlParameter[] parameters)
        {
            //实例化一个 SqlDataAdapter
            SqlDataAdapter da = new SqlDataAdapter(cmdText, ConStr);
            //设置参数
            da.SelectCommand.Parameters.AddRange(parameters);
            //实例化一个 DataTable
            DataTable dt = new DataTable();
            //将数据填充到 dt
            da.Fill(dt);
            return dt;
        }

        private void btnParameters_Click(object sender, EventArgs e)
        {
            BindData();
        }
    }
}
